package org.jeecg.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @ClassName CookieUtil
 * @Description TODO
 * @Author twm17
 * @Date 2021/6/26 13:22
 * @Version 1.0
 */
@Slf4j
public class CookieUtil {


    private final static String COOKIE_TOKEN_NAME = "securityID";
    private final static String COOKIE_BACKSTAGE_TOKEN_NAME = "backstage_securityID";


    public static String readLoginToken(HttpServletRequest request){
        Cookie[] cks = request.getCookies();

        if(cks != null){
            for(Cookie ck : cks){
                log.info("读 cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                if(StringUtils.equals(ck.getName(), CommonConstant.PREFIX_USER_TOKEN)){
                    log.info("返回 cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return null;
    }


    public static void writeLoginToken(HttpServletResponse response, String token, Integer loginTime){
        Cookie ck = new Cookie(CommonConstant.PREFIX_USER_TOKEN,token);
        ck.setPath("/");
        ck.setHttpOnly(false);

        if(Objects.isNull(loginTime)) {
            ck.setMaxAge(Integer.MAX_VALUE);
        }else {
            ck.setMaxAge(loginTime);
        }
        log.info("写 cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
        response.addCookie(ck);
    }



    public static void delLoginToken(HttpServletRequest request,HttpServletResponse response){
        Cookie[] cks = request.getCookies();
        if(cks != null){
            for(Cookie ck : cks){
                if(StringUtils.equals(ck.getName(),COOKIE_TOKEN_NAME)){
                    ck.setPath("/");
                    ck.setMaxAge(0);
                    log.info("删除 cookieName:{},cookieValue:{}",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }


}
